package com.yangye.picommon.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by youngyeah on 2019/8/29 0029
 */
@Component
public class OssUtil {

	@Value("${pi.oss.endpoint}")
	private String endpoint;

	@Value("${pi.oss.access-key-id}")
	private String accessKeyId;

	@Value("${pi.oss.access-key-secret}")
	private String accessKeySecret;

	@Value("${pi.oss.bucket-name}")
	private String bucketName;

	@Value("${pi.oss.access-url}")
	private String accessUrl;


	public OSS getOssClient() {
		OSSClientBuilder builder = new OSSClientBuilder();
		OSS oss = builder.build(endpoint, accessKeyId, accessKeySecret);
		return oss;
	}

	public String upload(InputStream is, String fileName) {
		OSS ossClient = this.getOssClient();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String tempFolder = sdf.format(Calendar.getInstance().getTime());
		String key = tempFolder + "/" + fileName;
		PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, is);
		String eTag = putObjectResult.getETag();
		System.out.println(eTag);
		return key;
	}

	public String getDownloadUrl(String key) {
		OSS ossClient = this.getOssClient();
		if (StringUtils.isNoneEmpty(key)) {
			return accessUrl + "/" + key;
		}
		return null;
	}
}
